#include "vtkFunctions.hpp"
#include "fieldFunctions.hpp"

namespace hms::vtk
{


/**
 * @brief Reads the values stored in the text of an xml node into an Eigen object.
 * The Eigen object has to already have the correct size.
 * 
 * The function accepts const references, because read() takes a const reference
 * and internally casts the const-ness away. This is the currently (June 2021)
 * preferred method for taking mutable Eigen expressions as function parameters,
 * according to the Eigen documentation
 * (http://eigen.tuxfamily.org/dox-devel/TopicFunctionTakingEigenTypes.html)
 * 
 * @param dataArray 
 * @param matrix 
 * @return
 */
template<typename Derived>
void textToMatrix(
	const xml::XMLElement* elem,
	const Eigen::DenseBase<Derived>& matrix
){
	if (elem){
		std::stringstream converter;
		converter << elem->GetText();
		try {
			read(converter, matrix);
		} catch ( const std::exception& e ){
			throw ParseError(
				"Could not read text after\n"
				+ nodeString(elem)
				+ "\nReason: " + e.what()
			);
		}
	} else
		throw ParseError( "textToMatrix: Element pointer is nullptr!" );
}

template<typename Derived, typename MeshType>
void textToFieldValues(
	const xml::XMLElement* elem,
	Eigen::DenseBase<Derived>& values,
	const MeshBase<MeshType>& mesh,
	Uniformity isUniform
){
	if (isUniform)
		textToMatrix(elem, values);
	else
		textToMatrix(elem, domainValues( values.derived(), mesh ) );
}

} // namespace hms::vtk
